#!/usr/bin/python3
# 文件名：server4multiClient.py

# 导入 socket、sys 模块
import json
import socket
import sys
from qqt_util import  *
# 创建 socket 对象
serversocket = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)

# 获取本地主机名
host = socket.gethostname()
from socketConfig import *
#port = 8096
#print(host,port)
# 绑定端口号
serversocket.bind(('127.0.0.1', port))

# 设置最大连接数，超过后排队
serversocket.listen(200)
#不堵塞
serversocket.setblocking(False)
clientsocket_cache = {}
data = {}
msg_pool = []
while True:
    # 建立客户端连接
    for addr, soc in clientsocket_cache.items():
        try:
            from_client = soc.recv(100)
            rsp  = from_client.decode('utf-8')
            data_received = json.loads(rsp)
            if 'operation' in data_received:
                if data_received['operation']in ['left','right','up','down','put_bubble']:
                    #
                    # bk_msg  = data_received
                    # bk_msg=json.dumps(bk_msg)+'\r\n'
                    # bk_msg = bk_msg.encode('utf-8')
                    # soc.send(bk_msg)
                    # 广播玩家操作
                    print('广播',data_received)
                    for addr, soc in clientsocket_cache.items():
                        bk_msg = data_received
                        bk_msg = json.dumps(bk_msg) + '\r\n'
                        bk_msg = bk_msg.encode('utf-8')
                        soc.send(bk_msg)

            # #方向判断
            # for direction in ['left','right','up','down']:
            #     if direction in rsp:
            #         print('direct = ',direction)
            #         x,y = data[addr].get('pos',(300,300))
            #         print('old xy',x,y)
            #         x,y = move(direction, 4, (x,y))
            #         print('new xy', x, y)
            #         data[addr]['pos'] = (x,y)
            #         msg = 'I get msg:  '+rsp + "\r\n"
            #         print('ready to ')
            #         soc.send(("pos:{},{}".format(x,y)+'\r\n').encode('utf-8'))
            #         print('sending')
            # # 操作判断
            # if 'operation' in rsp:
            #     print('operation received',rsp)
            #     if addr not in data:
            #         print('addr is not in data')
            #         data[addr] = {'pos': (300, 300), 'data': {'bubble': []}}
            #     x, y = data[addr].get('pos', (300, 300))
            #     print('old xy', x, y)
            #     x,y = int(x/40),int(y/40)
            #     data[addr]['data']['bubble'].append((x,y))
            #     data_ = "{}\r\n".format(json.dumps(data[addr]))
            #     soc.send(data_.encode('utf-8'))
        except Exception as e :
            #print('receive msg',e)

            pass
    # 防止异常
    try:
        clientsocket, addr = serversocket.accept()
        clientsocket_cache[addr] = clientsocket
        data[addr] = {'pos':(300,300),'data':{'bubble':[ ]}}
    except Exception as e:
        #print('saving',e)
        pass
#clientsocket.close()
serversocket.close()